"""会话控制器

处理会话管理相关的API接口
主要功能是创建会话并返回ID
"""

from fastapi import APIRouter, Depends, HTTPException
from loguru import logger

from app.services.session_service import SessionService
from app.schemas.session_schemas import SessionCreateRequest, SessionResponse, SessionUpdateRequest

router = APIRouter(prefix="/sessions", tags=["会话管理"])

def get_session_service() -> SessionService:
    """获取会话服务实例"""
    return SessionService()


@router.post("/", response_model=SessionResponse, summary="创建会话")
async def create_session(
    request: SessionCreateRequest,
    service: SessionService = Depends(get_session_service)
):
    """创建新会话
    
    在数据库创建一条记录，返回会话ID
    
    Args:
        request: 会话创建请求
        service: 会话服务实例
        
    Returns:
        SessionResponse: 创建的会话信息
    """
    try:
        session = await service.create_session(request.room_id, request.user_id)
        return session
        
    except ValueError as e:
        logger.warning(f"创建会话参数错误: {str(e)}")
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        logger.error(f"创建会话失败: {str(e)}")
        raise HTTPException(status_code=500, detail="创建会话失败")


@router.get("/{session_id}", response_model=SessionResponse, summary="查询会话")
async def get_session(
    session_id: str,
    service: SessionService = Depends(get_session_service)
):
    """查询会话信息
    
    Args:
        session_id: 会话ID
        service: 会话服务实例
        
    Returns:
        SessionResponse: 会话信息
    """
    try:
        session = await service.get_session(session_id)
        if not session:
            raise HTTPException(status_code=404, detail="会话不存在")
        return session
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"查询会话失败: {str(e)}")
        raise HTTPException(status_code=500, detail="查询会话失败")


@router.put("/{session_id}")
async def update_session(session_id: str, update_data: dict, service: SessionService = Depends(get_session_service)):
    """更新会话信息"""
    try:
        result = await service.update_session(session_id, update_data)
        if result:
            return {"status": "success", "data": result}
        else:
            raise HTTPException(status_code=404, detail="会话不存在")
    except Exception as e:
        logger.error(f"更新会话失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))
